import 'dart:math';

import 'package:flutter/material.dart';
import 'package:movie_ui_app/constans.dart';
import 'package:movie_ui_app/models/movie.dart';
import 'package:movie_ui_app/screens/home/components/movie_card.dart';

class MovieCarousel extends StatefulWidget {
  const MovieCarousel({Key key}) : super(key: key);

  @override
  _MovieCarouselState createState() => _MovieCarouselState();
}

class _MovieCarouselState extends State<MovieCarousel> {
  PageController _pageController;
  int initialPage = 1;
  @override
  void initState() {
    super.initState();
    _pageController =
        new PageController(viewportFraction: 0.8, initialPage: initialPage);
  }

  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: kDefaultPadding),
      child: AspectRatio(
        aspectRatio: 0.85, // 宽高比 宽/高
        child: PageView.builder(
          onPageChanged: (value) {
            setState(() {
              initialPage = value;
            });
          },
          controller: _pageController,
          itemCount: movies.length,
          itemBuilder: (context, index) => builderMovieSlider(index),
        ),
      ),
    );
  }

  Widget builderMovieSlider(int index) => AnimatedBuilder(
      animation: _pageController,
      builder: (context, child) {
        double value = 0;

        if (_pageController.position.haveDimensions) {
          value = index - _pageController.page;
          value = (value * 0.083).clamp(-1, 1);
        }
        return AnimatedOpacity(
          opacity: initialPage == index ? 1 : 0.4,
          duration: Duration(milliseconds: 350),
          child: Transform.rotate(
              angle: pi * value, child: MovieCard(movie: movies[index])),
        );
      });
}
